import { ref, computed } from "vue";
import { isvalidPhone } from "@/utils/utils";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import api from "@/api/index";
/*
*  处理登录和忘记密码逻辑
*/
const useAccount = () => {

  //手机号
  const phone = ref("");
  //密码
  const pwd = ref("");
  //确认密码
  const surePwd = ref("");
  //验证码
  const code = ref("");
  //是否能点击
  const disabled = ref(false);
  //定时器
  let interval = undefined;
  //倒计时时间
  const totalCount = ref(0);
  //按钮显示内容
  const btnText = computed(() => {
    return totalCount.value !== 0 ? `${totalCount.value}s` : "获取验证码";
  });

  const router = useRouter();
  //登录
  const loginHandle = () => {
    if (!isvalidPhone(phone.value)) {
      showToast("请输入正确手机号");
      return;
    }

    if (pwd.value.length == 0) {
      showToast("请输入验证码");
      return;
    }
   
    const params = {
      mobile:phone.value,
      password:pwd.value
    }
    api.authLogin(params).then((res) => {
      localStorage.setItem("accToken",res.data.accessToken);
      localStorage.setItem("ruleCode",res.data.ruleCode);
      router.replace({
        path: "/",
      });
    }).catch((msg) => {
      showToast(msg);
    }) 
    
  };

  //跳转忘记密码
  const forgetHandle = () => {
    if (!isvalidPhone(phone.value)) {
      showToast("请输入正确手机号");
      return;
    }

    if (pwd.value.length == 0) {
      showToast("请输入验证码");
      return;
    }
    // router.push("forgetPwd");
    showToast("请联系管理员修改密码");
  };

  //返回登录
  const gobackHandle = () => {
    router.back();
  };


  //验证码点击
  const getCode = () => {

    if (!isvalidPhone(phone.value)) {
      showToast("请输入正确手机号");
      return;
    }

    // 按钮60秒倒计时
    disabled.value = true;
    totalCount.value = 60;
    sendCode();
    interval = setInterval(() => {
      totalCount.value--;
      if (totalCount.value === 0) {
        clearInterval(interval);
        disabled.value = false;
      }
    }, 1000);
  };

  //发送验证码
  const sendCode = () => {
    // console.log("发送验证码接口");
  };

  return {
    phone,
    pwd,
    surePwd,
    code,
    disabled,
    interval,
    totalCount,
    btnText,
    getCode,
    sendCode,
    loginHandle,
    forgetHandle,
    gobackHandle
  };
};

export { useAccount };
